package com.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.constants.Constants;
import com.dao.GongyingshangDao;
import com.entity.*;
import com.entity.vo.WeChatAccessTokenVo;
import com.entity.vo.WeChatMiniAuthorizeVO;
import com.service.ConfigService;
import com.service.OperateLogService;
import com.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.annotation.IgnoreAuth;

import com.entity.view.GongyingshangView;

import com.service.GongyingshangService;
import com.service.TokenService;

import java.io.IOException;

/**
 * 供应商
 * 后端接口
 * @author 
 * @email 
 * @date 2022-05-13 10:40:26
 */
@RestController
@RequestMapping("/gongyingshang")
public class GongyingshangController {
	@Autowired
	private GongyingshangService gongyingshangService;


	@Autowired
	private GongyingshangDao gongyingshangDao;


	@Autowired
	private TokenService tokenService;


	@Autowired
	private ConfigService configService;


	@Autowired
	private RestTemplateUtil restTemplateUtil;


	@Autowired
	private OperateLogService operateLogService;
	/**
	 * 登录
	 */
	@IgnoreAuth
	@RequestMapping(value = "/login")
	public R login(String username, String password, String captcha, HttpServletRequest request) {
		GongyingshangEntity user = gongyingshangService.selectOne(new EntityWrapper<GongyingshangEntity>().eq("gongyingshangmingcheng", username));
		if(user==null || !user.getMima().equals(password)) {
			return R.error("账号或密码不正确");
		}

		String token = tokenService.generateToken(user.getId(), username,"gongyingshang",  "供应商" );
		return R.ok().put("token", token);
	}

	@IgnoreAuth
	@RequestMapping(value = "/wechatAutoLogin",method = RequestMethod.POST)
	public R wechatAutoLogin(@RequestBody @Validated WxBindingPhoneEntity wxBindingPhoneEntity) {


		String code = wxBindingPhoneEntity.getOpcode();
		// 参数校验
		if (StrUtil.isBlank(code)) {
			return R.error("小程序获取code不能为空");
		}

		String appId = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "routine_appid")).getValue();

		if (StringUtils.isBlank(appId)) {
			return R.error("微信小程序appId未设置");
		}
		String secret = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "routine_appsecret")).getValue();

		if (StrUtil.isBlank(secret)) {
			return R.error("微信小程序secret未设置");
		}


		WeChatMiniAuthorizeVO weChatMiniAuthorizeVO =  miniAuthCode(wxBindingPhoneEntity.getOpcode(),appId, secret);

		if(ObjectUtil.isNotNull(weChatMiniAuthorizeVO) && weChatMiniAuthorizeVO.getOpenId() != null){
			Wrapper<GongyingshangEntity> gongyingshangEntityWrapper = new EntityWrapper<GongyingshangEntity>().eq("openid", weChatMiniAuthorizeVO.getOpenId());
			GongyingshangEntity gongyingshang2 =  gongyingshangService.selectOne(gongyingshangEntityWrapper);

			if(gongyingshang2!=null){
				String token = tokenService.generateToken(gongyingshang2.getId(), gongyingshang2.getLianxidianhua(),"gongyingshang",  "供应商" );
				return R.ok().put("token", token).put("user",gongyingshang2);
			}
		}
		return R.ok();

	}


	@IgnoreAuth
	@RequestMapping(value = "/wechatLogin",method = RequestMethod.POST)
	public R wechatLogin(@RequestBody @Validated WxBindingPhoneEntity wxBindingPhoneEntity) {


		String code = wxBindingPhoneEntity.getCode();
		// 参数校验
		if (StrUtil.isBlank(code)) {
			return R.error("小程序获取手机号code不能为空");
		}
		if (StrUtil.isBlank(wxBindingPhoneEntity.getEncryptedData())) {
			return R.error("小程序获取手机号加密数据不能为空");
		}
		if (StrUtil.isBlank(wxBindingPhoneEntity.getIv())) {
			return R.error("小程序获取手机号加密算法的初始向量不能为空");
		}

		String appId = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "routine_appid")).getValue();

		if (StringUtils.isBlank(appId)) {
			return R.error("微信小程序appId未设置");
		}
		String secret = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "routine_appsecret")).getValue();

		if (StrUtil.isBlank(secret)) {
			return R.error("微信小程序secret未设置");
		}


		WeChatMiniAuthorizeVO weChatMiniAuthorizeVO =  miniAuthCode(wxBindingPhoneEntity.getOpcode(),appId, secret);

		if(ObjectUtil.isNotNull(weChatMiniAuthorizeVO) && weChatMiniAuthorizeVO.getOpenId() != null){
			Wrapper<GongyingshangEntity> gongyingshangEntityWrapper = new EntityWrapper<GongyingshangEntity>().eq("openid", weChatMiniAuthorizeVO.getOpenId());
			GongyingshangEntity gongyingshang2 =  gongyingshangService.selectOne(gongyingshangEntityWrapper);

		    if(gongyingshang2!=null){
				String token = tokenService.generateToken(gongyingshang2.getId(), gongyingshang2.getLianxidianhua(),"gongyingshang",  "供应商" );
				return R.ok().put("token", token).put("user",gongyingshang2);
			}
		}

		String url = StrUtil.format(Constants.WECHAT_ACCESS_TOKEN_URL, appId, secret);
		JSONObject data = restTemplateUtil.getData(url);

		if (ObjectUtil.isNull(data)) {
			return R.error("微信平台接口异常，没任何数据返回！");
		}
		if (data.containsKey("errcode") && !data.getString("errcode").equals("0")) {
			if (data.containsKey("errmsg")) {
				// 保存到微信异常表
				return R.error("微信接口调用失败：" + data.getString("errcode") + data.getString("errmsg"));
			}
		}
		WeChatAccessTokenVo weChatAccessTokenVo = JSONObject.parseObject(data.toJSONString(), WeChatAccessTokenVo.class);

		String getPhoneUrl = StrUtil.format(Constants.WEBCHAT_GETPHONE, weChatAccessTokenVo.getAccess_token());
		Map<String,Object> map = new HashMap<>();
		map.put("code", code);

		String res = restTemplateUtil.postMapData(getPhoneUrl, map);

		JSONObject jsonObject =  JSONObject.parseObject(res);

		if (ObjectUtil.isNull(jsonObject)) {
			return R.error("微信平台接口异常，没任何数据返回！");
		}
		if (jsonObject.containsKey("errcode") && !jsonObject.getString("errcode").equals("0")) {
			if (jsonObject.containsKey("errmsg")) {
				// 保存到微信异常表
				return R.error("微信接口调用失败：" + jsonObject.getString("errcode") + jsonObject.getString("errmsg"));
			}
		}
		JSONObject phoneInfo = (JSONObject) jsonObject.get("phone_info");
		if(ObjectUtil.isNull(phoneInfo)) {
			return R.error("微信小程序获取手机号解密失败");
		}
		String phone = phoneInfo.getString("phoneNumber");
		if (StrUtil.isBlank(phone)) {
			return R.error("微信小程序获取手机号没有有效的手机号");
		}
		Wrapper<GongyingshangEntity> wrapper = new EntityWrapper<GongyingshangEntity>().eq("lianxidianhua", phone);
		GongyingshangEntity gongyingshangEntity =  gongyingshangService.selectOne(wrapper);

		if(gongyingshangEntity !=null) {
			if(gongyingshangEntity.getOpenid() == null || gongyingshangEntity.getOpenid().isEmpty()){
				gongyingshangEntity.setOpenid(weChatMiniAuthorizeVO.getOpenId());
				gongyingshangDao.updateById(gongyingshangEntity);
			}
			String token = tokenService.generateToken(gongyingshangEntity.getId(), phone,"gongyingshang",  "供应商" );
			return R.ok().put("token", token).put("user",gongyingshangEntity);
		} else {
			GongyingshangEntity gongyingshang = new GongyingshangEntity();
			gongyingshang.setLianxidianhua(phone);
			gongyingshang.setShibiema(phone);
			gongyingshang.setAddtime(CommonUtil.nowDateTime());
			gongyingshang.setMima("123456");
			gongyingshang.setStatus(0);
			gongyingshang.setOpenid(weChatMiniAuthorizeVO.getOpenId());
			gongyingshangDao.insert(gongyingshang);

			String token = tokenService.generateToken(gongyingshang.getId(), phone,"gongyingshang",  "供应商" );

			return R.ok().put("token", token).put("user",gongyingshang);
		}


	}



	public WeChatMiniAuthorizeVO miniAuthCode(String code, String appId, String secret) {


		String url = StrUtil.format(Constants.WECHAT_MINI_SNS_AUTH_CODE2SESSION_URL, appId, secret, code);
		JSONObject data = restTemplateUtil.getData(url);
		if (ObjectUtil.isNull(data)) {
			throw new EIException("微信平台接口异常，没任何数据返回！");
		}
		if (data.containsKey("errcode") && !data.getString("errcode").equals("0")) {
			if (data.containsKey("errmsg")) {
				// 保存到微信异常表
				throw new EIException("微信接口调用失败：" + data.getString("errcode") + data.getString("errmsg"));
			}
		}
		return JSONObject.parseObject(data.toJSONString(), WeChatMiniAuthorizeVO.class);
	}



	/**
     * 注册
     */
	@IgnoreAuth
    @RequestMapping("/register")
    public R register(@RequestBody GongyingshangEntity gongyingshang){
    	//ValidatorUtils.validateEntity(gongyingshang);
    	GongyingshangEntity user = gongyingshangService.selectOne(new EntityWrapper<GongyingshangEntity>().eq("gongyingshangmingcheng", gongyingshang.getGongyingshangmingcheng()));
		if(user!=null) {
			return R.error("注册用户已存在");
		}
		Long uId = new Date().getTime();
		gongyingshang.setId(uId);
        gongyingshangService.insert(gongyingshang);
        return R.ok();
    }

	
	/**
	 * 退出
	 */
	@RequestMapping("/logout")
	public R logout(HttpServletRequest request) {
		request.getSession().invalidate();
		return R.ok("退出成功");
	}
	
	/**
     * 获取用户的session用户信息
     */
    @RequestMapping("/session")
    public R getCurrUser(HttpServletRequest request){
    	Long id = (Long)request.getSession().getAttribute("userId");
        GongyingshangEntity user = gongyingshangService.selectById(id);
        return R.ok().put("data", user);
    }
    
    /**
     * 密码重置
     */
    @IgnoreAuth
	@RequestMapping(value = "/resetPass")
    public R resetPass(String username, HttpServletRequest request){
    	GongyingshangEntity user = gongyingshangService.selectOne(new EntityWrapper<GongyingshangEntity>().eq("gongyingshangmingcheng", username));
    	if(user==null) {
    		return R.error("账号不存在");
    	}
        user.setMima("123456");
        gongyingshangService.updateById(user);
        return R.ok("密码已重置为：123456");
    }


    /**
     * 后端列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params,GongyingshangEntity gongyingshang,
		HttpServletRequest request){
        EntityWrapper<GongyingshangEntity> ew = new EntityWrapper<GongyingshangEntity>();
		PageUtils page = gongyingshangService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, gongyingshang), params), params));

        return R.ok().put("data", page);
    }
    
    /**
     * 前端列表
     */
	@IgnoreAuth
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params,GongyingshangEntity gongyingshang, 
		HttpServletRequest request){
        EntityWrapper<GongyingshangEntity> ew = new EntityWrapper<GongyingshangEntity>();
		PageUtils page = gongyingshangService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, gongyingshang), params), params));
        return R.ok().put("data", page);
    }

	/**
     * 列表
     */
    @RequestMapping("/lists")
    public R list( GongyingshangEntity gongyingshang){
       	EntityWrapper<GongyingshangEntity> ew = new EntityWrapper<GongyingshangEntity>();
      	ew.allEq(MPUtil.allEQMapPre( gongyingshang, "gongyingshang")); 
        return R.ok().put("data", gongyingshangService.selectListView(ew));
    }

	 /**
     * 查询
     */
    @RequestMapping("/query")
    public R query(GongyingshangEntity gongyingshang){
        EntityWrapper< GongyingshangEntity> ew = new EntityWrapper< GongyingshangEntity>();
 		ew.allEq(MPUtil.allEQMapPre( gongyingshang, "gongyingshang")); 
		GongyingshangView gongyingshangView =  gongyingshangService.selectView(ew);
		return R.ok("查询供应商成功").put("data", gongyingshangView);
    }
	
    /**
     * 后端详情
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
        GongyingshangEntity gongyingshang = gongyingshangService.selectById(id);
        return R.ok().put("data", gongyingshang);
    }

    /**
     * 前端详情
     */
	@IgnoreAuth
    @RequestMapping("/detail/{id}")
    public R detail(@PathVariable("id") Long id){
        GongyingshangEntity gongyingshang = gongyingshangService.selectById(id);
        return R.ok().put("data", gongyingshang);
    }
    



    /**
     * 后端保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody GongyingshangEntity gongyingshang, HttpServletRequest request){
    	gongyingshang.setId(new Date().getTime()+new Double(Math.floor(Math.random()*1000)).longValue());
    	//ValidatorUtils.validateEntity(gongyingshang);
    	GongyingshangEntity user = gongyingshangService.selectOne(new EntityWrapper<GongyingshangEntity>().eq("gongyingshangmingcheng", gongyingshang.getGongyingshangmingcheng()));
		if(user!=null) {
			return R.error("用户已存在");
		}
		gongyingshang.setStatus(1);
        gongyingshangService.insert(gongyingshang);


		OperateLogEntity operateLogEntity = new OperateLogEntity();
		operateLogEntity.setTitle("创建供应商:"+gongyingshang.getGongyingshangmingcheng());
		operateLogEntity.setAction("create");
		operateLogEntity.setOperatorId((long)request.getSession().getAttribute("userId"));
		operateLogEntity.setOperatorRole(request.getSession().getAttribute("role").toString());
		operateLogEntity.setOperatorName(request.getSession().getAttribute("username").toString());
		operateLogEntity.setMark(request.getSession().getAttribute("username").toString()+
				"创建了:"+gongyingshang.getGongyingshangmingcheng());
		// 获取当前时间的毫秒数
		long currentTimeMillis = System.currentTimeMillis();

		// 使用毫秒数创建Date对象
		Date currentTime = new Date(currentTimeMillis);
		operateLogEntity.setCreateTime(currentTime);
		operateLogService.insert(operateLogEntity);

        return R.ok();
    }
    
    /**
     * 前端保存
     */
    @RequestMapping("/add")
    public R add(@RequestBody GongyingshangEntity gongyingshang, HttpServletRequest request){
    	gongyingshang.setId(new Date().getTime()+new Double(Math.floor(Math.random()*1000)).longValue());
    	//ValidatorUtils.validateEntity(gongyingshang);
    	GongyingshangEntity user = gongyingshangService.selectOne(new EntityWrapper<GongyingshangEntity>().eq("gongyingshangmingcheng", gongyingshang.getGongyingshangmingcheng()));
		if(user!=null) {
			return R.error("用户已存在");
		}
		gongyingshang.setStatus(0);
        gongyingshangService.insert(gongyingshang);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @Transactional
    public R update(@RequestBody GongyingshangEntity gongyingshang, HttpServletRequest request){
        //ValidatorUtils.validateEntity(gongyingshang);
        gongyingshangService.updateById(gongyingshang);//全部更新

		OperateLogEntity operateLogEntity = new OperateLogEntity();
		operateLogEntity.setTitle("更新供应商:"+gongyingshang.getGongyingshangmingcheng());
		operateLogEntity.setAction("edit");
		operateLogEntity.setOperatorId((long)request.getSession().getAttribute("userId"));
		operateLogEntity.setOperatorRole(request.getSession().getAttribute("role").toString());
		operateLogEntity.setOperatorName(request.getSession().getAttribute("username").toString());
		operateLogEntity.setMark(request.getSession().getAttribute("username").toString()+
				"更新了:"+gongyingshang.getGongyingshangmingcheng());
		// 获取当前时间的毫秒数
		long currentTimeMillis = System.currentTimeMillis();

		// 使用毫秒数创建Date对象
		Date currentTime = new Date(currentTimeMillis);
		operateLogEntity.setCreateTime(currentTime);
		operateLogService.insert(operateLogEntity);
        return R.ok();
    }
    

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids,  HttpServletRequest request){
        gongyingshangService.deleteBatchIds(Arrays.asList(ids));

		OperateLogEntity operateLogEntity = new OperateLogEntity();
		operateLogEntity.setTitle("删除供应商:"+   Arrays.toString(ids));
		operateLogEntity.setAction("delete");
		operateLogEntity.setOperatorId((long)request.getSession().getAttribute("userId"));
		operateLogEntity.setOperatorRole(request.getSession().getAttribute("role").toString());
		operateLogEntity.setOperatorName(request.getSession().getAttribute("username").toString());
		operateLogEntity.setMark(request.getSession().getAttribute("username").toString()+
				"删除了供应商:"+ Arrays.toString(ids));
		// 获取当前时间的毫秒数
		long currentTimeMillis = System.currentTimeMillis();

		// 使用毫秒数创建Date对象
		Date currentTime = new Date(currentTimeMillis);
		operateLogEntity.setCreateTime(currentTime);
		operateLogService.insert(operateLogEntity);
        return R.ok();
    }
    
    /**
     * 提醒接口
     */
	@RequestMapping("/remind/{columnName}/{type}")
	public R remindCount(@PathVariable("columnName") String columnName, HttpServletRequest request, 
						 @PathVariable("type") String type,@RequestParam Map<String, Object> map) {
		map.put("column", columnName);
		map.put("type", type);
		
		if(type.equals("2")) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c = Calendar.getInstance();
			Date remindStartDate = null;
			Date remindEndDate = null;
			if(map.get("remindstart")!=null) {
				Integer remindStart = Integer.parseInt(map.get("remindstart").toString());
				c.setTime(new Date()); 
				c.add(Calendar.DAY_OF_MONTH,remindStart);
				remindStartDate = c.getTime();
				map.put("remindstart", sdf.format(remindStartDate));
			}
			if(map.get("remindend")!=null) {
				Integer remindEnd = Integer.parseInt(map.get("remindend").toString());
				c.setTime(new Date());
				c.add(Calendar.DAY_OF_MONTH,remindEnd);
				remindEndDate = c.getTime();
				map.put("remindend", sdf.format(remindEndDate));
			}
		}
		
		Wrapper<GongyingshangEntity> wrapper = new EntityWrapper<GongyingshangEntity>();
		if(map.get("remindstart")!=null) {
			wrapper.ge(columnName, map.get("remindstart"));
		}
		if(map.get("remindend")!=null) {
			wrapper.le(columnName, map.get("remindend"));
		}


		int count = gongyingshangService.selectCount(wrapper);
		return R.ok().put("count", count);
	}
	







}
